﻿Imports System.IO

Public Class ErrorView
    Private Sub ListView_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListView.MouseDoubleClick
        If e.Button = MouseButtons.Left Then
            If Not IsNothing(GetChildAtPoint(e.Location)) Then
                GotoError(ListView.SelectedIndices(0))
            End If
        End If
    End Sub

    Public Sub PrevError()
        Dim nextindex As Integer = ListView.SelectedIndices(0) - 1
        If nextindex >= 0 Then
            ListView.SelectedIndices.Clear()
            ListView.SelectedIndices.Add(nextindex)
        End If
    End Sub

    Public Sub NextError()
        Dim nextindex As Integer = ListView.SelectedIndices(0) + 1
        If nextindex < ListView.Items.Count Then
            ListView.SelectedIndices.Clear()
            ListView.SelectedIndices.Add(nextindex)
        End If
    End Sub

    Public Sub GotoError(ByVal index As Integer)
        ListView.SelectedIndices.Clear()
        ListView.SelectedIndices.Add(index)

        Dim fullname As String = ListView.SelectedItems(0).SubItems(3).Text

        If Not File.Exists(fullname) Then
            ' Bail out if the file does not exist
            Exit Sub
        End If

        Dim line As Integer = CType(ListView.SelectedItems(0).SubItems(2).Text, Integer)

        If line < 0 Then
            line = -line
        End If

        Dim leaf As String = fullname.Substring(fullname.LastIndexOf("\") + 1, fullname.Length - fullname.LastIndexOf("\") - 1)

        Dim tab = MainForm.EditorTabManager.AddTab(leaf, New Project.ProjectFile(fullname))

        If Not IsNothing(tab) Then
            tab.ScintillaEditor.GoTo.Line(line)
            tab.ScintillaEditor.Caret.LineNumber = line - 1
            tab.ScintillaEditor.Caret.Position += tab.ScintillaEditor.Lines(line - 1).Length
            tab.ScintillaEditor.Selection.Start = tab.ScintillaEditor.Selection.End
            tab.ScintillaEditor.Scrolling.ScrollToCaret()
            tab.ScintillaEditor.Focus()
        End If
    End Sub

End Class
